<template>
  <section>
    <el-table ref="settable"
              v-loading="loading"
              :data="currentData"
              height="300px">
      <el-table-column type="index"
                       align="center"
                       label="序号">
      </el-table-column>
      <template v-for="(column, index) in columns">
        <el-table-column :key="index"
                         :prop="column.prop"
                         :label="column.label"
                         :show-overflow-tooltip="false"
                         :width="['name'].includes(column.prop) ? '225':''"
                         :render-header="renderHeader">
          <template slot-scope="scope">
            <div v-if="column.prop === 'barcode'">
              <el-input v-model="scope.row[column.prop]"
                        placeholder="请输入物料编码"
                        maxlength="30"
                        @input="handleInput($event, column.prop, scope.$index)" />
            </div>
            <div v-else-if="column.prop === 'name'">
              <el-input v-model="scope.row[column.prop]"
                        placeholder="请输入物品名称"
                        maxlength="100"
                        :class="scope.row[column.prop+'Warn'] ? 'warnBorder' : (scope.row.goodsNameErr ? 'errorBorder':'')"
                        @input="handleInput($event, column.prop, scope.$index)" />
              <div v-if="scope.row[column.prop+'Warn']"
                   class="warn">{{scope.row[column.prop+'Warn']}}</div>
              <div v-if="scope.row.goodsNameErr"
                   class="error">{{scope.row.goodsNameErr}}</div>
            </div>
            <div v-else-if="['spec', 'weight', 'volume', 'value', 'type'].includes(column.prop)">
              {{scope.row[column.prop]}}
              <!-- <el-input v-model="scope.row[column.prop]"
                        placeholder="请输入规格"
                        maxlength="30"
                        disabled
                        @input="handleInput($event, column.prop, scope.$index)" /> -->
            </div>
            <!-- <div v-else-if="column.prop === 'weight'">
              <el-input v-model="scope.row[column.prop]"
                        placeholder="请输入重量（kg）"
                        oninput="this.value=(this.value.match(/\d{0,5}(\.\d{0,4})?/)||[''])[0];"
                        disabled
                        @input="handleInput($event, column.prop, scope.$index)" />
            </div>
            <div v-else-if="column.prop === 'volume'">
              <el-input v-model="scope.row[column.prop]"
                        placeholder="请输入体积（m³）"
                        oninput="this.value=(this.value.match(/\d{0,3}(\.\d{0,6})?/)||[''])[0];"
                        disabled
                        @input="handleInput($event, column.prop, scope.$index)" />
            </div> -->
            <div v-else-if="column.prop === 'quantity'">
              <el-input v-model="scope.row[column.prop]"
                        placeholder="请输入数量"
                        oninput="this.value=(this.value.match(/\d{0,8}(\d{0,0})?/)||[''])[0];"
                        @input="handleInput($event, column.prop, scope.$index)" />
            </div>
            <!-- <div v-else-if="column.prop === 'value'">
              <el-input v-model="scope.row[column.prop]"
                        placeholder="请输入价值"
                        oninput="this.value=(this.value.match(/\d{0,7}(\.\d{0,2})?/)||[''])[0];"
                        disabled
                        @input="handleInput($event, column.prop, scope.$index)" />
            </div>
            <div v-else-if="column.prop === 'type'">
              <div class="flex-start">
                <el-input v-model="scope.row[column.prop]"
                          placeholder="请选择或输入"
                          maxlength="30"
                          disabled
                          @input="handleInput($event, column.prop, scope.$index)" />
              </div>
            </div> -->
            <div v-else-if="column.prop === 'batchNo'">
              <el-input v-model="scope.row[column.prop]"
                        placeholder="请输入批次"
                        maxlength="20"
                        @input="handleInput($event, column.prop, scope.$index)" />
            </div>
            <div v-else>
              <el-input v-model="scope.row[column.prop]"
                        placeholder="请输入"
                        maxlength="100"
                        @input="handleInput($event, column.prop, scope.$index)" />
            </div>
            <div v-if="scope.row[column.prop+'Err']"
                 style="color:red">{{scope.row[column.prop+'Err']}}</div>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <select-goods v-if="showGoods"
                  :type="type"
                  :value="goodsValue"
                  :customer-id="record.customerId"
                  :dialog-visible.sync="showGoods"
                  :filter="{}"
                  :style="`left:260px;top:${lastIndex * 60 + 580 }px`"
                  @selectRow="selectRow" />
  </section>
</template>

<script>
import SelectGoods from "@views/createOrder/createOrder/components/SelectGoods.vue";
export default {
  name: "Goods",
  components: { SelectGoods },
  props: {
    record: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      loading: false,
      showGoods: false, //物品组件
      type: "", //物品查询名称
      goodsValue: "", //物品查询值
      currentData: [], // 数据源
      lastIndex: 0,
      columns: [
        { label: "物料编码", prop: "barcode" },
        { label: "*物品名称", prop: "name" },
        { label: "*规格", prop: "spec" },
        { label: "*重量（kg）", prop: "weight" },
        { label: "*体积（m³）", prop: "volume" },
        { label: "*数量", prop: "quantity" },
        { label: "*价值", prop: "value" },
        { label: "*物品类型", prop: "type" },
        { label: "批次", prop: "batchNo" },
        { label: "备注", prop: "remarks" },
      ],
    };
  },
  created () {
    this.currentData = JSON.parse(JSON.stringify(this.record?.goodsList));
    // 发货方错误
    let customerNameErr = this.record?.errors.filter(v => v.field === 'customerName')
    this.currentData.map(item => {
      if (item.errors && item.errors.length) {
        item.errors.map(ele => {
          // let field = ele.field.split(".")[1];
          item[`${ele.field}Err`] = ele.message;
          if (ele.field === 'goodsName') {
            item.goodsNameErr = `物品不存在，请重新选择`
          }
        })
      }
      if (customerNameErr.length) {
        item.goodsNameErr = `物品不存在，请重新选择`
      }
      if (item.warnings && item.warnings.length) {
        item.warnings.map(ele => {
          item.nameWarn = `存在同名物品，请确认`;
        })
      }
    })
  },
  methods: {
    handleInput (val, type, index) {
      if (val) {
        this.currentData[index][`${type}Err`] = null;
      }
      // 物品名称和编码输入
      if (['barcode', 'name'].includes(type)) {
        if (val.length > 1) {
          this.type = type;
          this.goodsValue = val;
          this.showGoods = true;
          this.lastIndex = index;
        }
        // 物品名称和编码改变，清空物品
        let arr = [...this.currentData];
        arr[index] = {
          rowIndex: this.currentData[index].rowIndex,
          barcode: this.currentData[index].barcode,
          name: this.currentData[index].name,
          spec: null,
          weight: null,
          volume: null,
          quantity: this.currentData[index].quantity,
          value: null,
          type: null,
          batchNo: this.currentData[index].batchNo,
          remarks: this.currentData[index].remarks,
          warnings: [], nameWarn: null,
          goodsNameErr: `物品${type === 'name' ? '名称' : '编码'}发生改变，请重新选择`
        }
        this.currentData = arr
      }
      // 根据数量计算总体积、重量、价值
      if (['quantity'].includes(type)) {
        this.$emit("total", this.currentData, 2)
      }
    },
    // 选择物品
    selectRow (row) {
      let arr = [...this.currentData];
      arr[this.lastIndex] = {
        ...this.currentData[this.lastIndex],
        ...row,
        barcode: row?.barcode || null,
        weight: row.netWeight,
        warnings: [], nameWarn: null, goodsNameErr: null
      }
      this.currentData = arr
      this.$emit("total", this.currentData, 2)
      console.log("selectRow", arr[this.lastIndex])
    },
    renderHeader (h, { column, $index }) {
      if (['*重量（kg）', '*体积（m³）', '*价值'].includes(column.label)) {
        const labelArr = { 4: '重量', 5: '体积', 7: '价值' }
        let val = labelArr[$index];

        return [column.label,
        h(
          'el-tooltip',
          {
            props: {
              content: `单个物品${val}`,
              placement: 'top'
            }
          },
          [h('span', { class: { 'el-icon-question': true } })]
        )]
      } else {
        return column.label
      }
    }
  }
};
</script>

<style lang="scss" scoped>
$warn-color: var(--prev-color-primary);
.warn {
  color: var(--prev-color-primary);
}
/deep/ .warnBorder .el-input__inner {
  // border-color: #c0c4cc;
  border-color: $warn-color;
}
/deep/ .errorBorder .el-input__inner {
  // border-color: #c0c4cc;
  border-color: var(--prev-color-text-purered);
}
.error {
  color: var(--prev-color-text-purered);
}
.mt10 {
  margin-top: 10px;
}
.flex-start {
  display: flex;
  justify-content: flex-start;
}
.flex-end {
  display: flex;
  justify-content: flex-end;
}
</style>
